/*
 * Редактор страницы с расширенными ссылками. 
 */
(function() {
	if(window.ELEDITOR) return;
	window.ELEDITOR || (window.ELEDITOR = function() {
		eleditor = {
			/**
			 * Задать текст для редактирования.
			 */
			setData : function(text) {
				eleditor.snipesections.setText(text);
			},

			/**
			 * Получить редактируемый текст.
			 */
			getData : function() {
				return "123 foo";
			},

			putPageLink : function(pageLink) {
				eleditor.snipe.putPageLink(pageLink);
			},

			/**
			 * Проверка обновления содержимого редактора.
			 */
			checkDirty : function() {
				return true;
			},

			/**
			 * Сброс обновленного содержимого редактора.
			 */
			resetDirty : function() {
			},

			/**
			 * Создание элементов редактора в DOM.
			 */
			appendTo : function(el) {
				// ?? :FVK:deprecated: ?? eleditor.previewcache = null;
				var editform;
				var textarea;
				var snipe;
				// ?? :FVK:deprecated: ?? var preview;
				// ?? :FVK:deprecated: ?? var isLivePreview;
				var sectionsDropDown;

				el.className = 'page-content';
				__setMainHTML(el);

			    //editform = element;
				editform = el.getElementById('editform');

				eleditor.textarea = textarea = this.getFormElement(".editor");
			    // ?? :FVK:deprecated: ?? preview = this.getFormElement(".ajaxpreview");

			    // ?? :FVK:deprecated: ?? eleditor.isLivePreview = isLivePreview = this.getFormElement("[data-cmd=livepreview]") || {};

			    // :FVK: onbeforeunload( );

			    Wiki.initialize(); // initialize all registered behaviors
			    Wiki.update(); // --OLD_source-- Wiki.domready();

			    if(!textarea) return;

			    eleditor.snipe = snipe = new Snipe( textarea, {
			        container: editform,
			        undoBtns: {
			            undo: this.getFormElement("[data-cmd=undo]"),
			            redo: this.getFormElement("[data-cmd=redo]")
			        },
			        snippets: Wiki.Snips,
			        directsnips: Wiki.DirectSnips,
			        // onChange: this.livepreview.debounce(500) ~~ :FVK:
			    });

			    if( sectionsDropDown = this.getFormElement(".sections") ) {
			    	eleditor.snipesections = new Snipe.Sections( sectionsDropDown, {
			           snipe: snipe,
			           parser: __jspwikiSectionParser  //callback
			        });
			    }

			    /// :FVK: eleditor.snipe.subscribeToChanging()
			    
			    Wiki.configPrefs( editform, function(cmd, isChecked) {
			        snipe.set(cmd, isChecked); //and snipe will fire the change event
			    });

			    // :FVK:deprecated: Wiki.resizer( snipe.toElement(), function(h){ preview.setStyle("height", h); });

			    return eleditor;
			},

		// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

			resize : function(width, height) {
				var workarea = eleditor.snipesections.getWorkArea();
				workarea.setStyle("height", height - 64);
			},

			/*
			 Function: getFormElement
				Helper function : lookup first matching descendant DOM element from the editform
			 */
			getFormElement : function(selector) {
				return editform.getElement(selector);
			},

			/*
			 Function: livepreview
				Linked as onChange handler to the SnipEditor.
				Make AJAX call to the backend to convert the contents of the textarea
				(wiki markup) to HTML.
				TODO: should work bothways. wysiwyg <-> wikimarkup
			 */
			livepreview: function() {
				/* ?? :FVK:deprecated: ??
				if( !eleditor.isLivePreview.checked ) {
					//cleanup the preview area
					console.log("cleanup");
					if( eleditor.previewcache ) {
						preview.empty();
						eleditor.previewcache = null;
					}
				} else if( eleditor.previewcache != text ) {
					eleditor.previewcache = text;
					//return preview.set("html",preview.get("html")+" Lorem ipsum"); //test code

					//console.log("**** invoke Request.HTML ",previewcache, wiki.XHRPreview)
					new Request.HTML({
						url: wiki.XHRPreview,
						data: {
							page: wiki.PageName,
							wikimarkup: text
						},
						update: preview,
						onRequest: function() {
							preview.addClass(loading);
						},
						onComplete: function() {
							preview.removeClass(loading);
							wiki.update();
						}
					}).send();
				}*/
			}, // livepreview: function()


		// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		};
		return eleditor;
	}());
}());

/*
Function: jspwikiSectionParser
    Convert a jspwiki-markup page into an array of page sections.
    Sections are marked by jspwiki headers:  !, !!  or !!!

    This function is used as a callback for [Snip.Sections]

Returns:
    This function returns a array of objects [{title, start, depth}]
    title - (string) plain title of the section (no wiki markup)
    start - (number) offset within the text string where this section starts
    depth - (number) nesting level of the section 0,1...n
*/
function __jspwikiSectionParser( text ) {
    var result = [];
    var DELIM = "\u00a4";
    var tt = text
    		// mask confusing header markup inside a {{{ ... }}} but keep length of the text unchanged!
    		.replace(/\{\{\{([\s\S]*?)\}\}\}/g, function(match) {
    			return match.replace( /^!/mg, " " );
    		})
    		// break string up into array of headers and section-bodies :
    		// [0] : text prior to the first header
    		// [1,odd] : header markup !, !! or !!!
    		// [2,even] : remainder of the section, starting with header title
           .replace( /^([!]{1,3})/mg, DELIM + "$1" + DELIM )
           .split(DELIM);
    var pos = tt.shift().length;  //get length of the first element, prior to first section
    var count = tt.length;
    var i, hlen, title;

    for( i = 0; i < count; i = i + 2 ) {
        hlen = tt[i].length;
        //take first line
        title = tt[i + 1].split(/[\r\n]/)[0]
            //remove unescaped(~) inline wiki markup __,"",{{,}}, %%(*), /%
            .replace(/(^|[^~])(__|""|\{\{|\}\}|%%\([^\)]+\)|%%\S+\s|%%\([^\)]+\)|\/%)/g, "$1")

            //and remove wiki-markup escape chars ~
            .replace(/~([^~])/g, "$1");

        //depth: convert length of header markup (!!!,!!,!) into #depth-level:  3,2,1 => 0,1,2
        result.push({ title: title, start: pos, depth: 3 - hlen });
        pos += hlen + tt[i + 1].length;
    }

    return result;
}; // jspwikiSectionParser: function( text )


function __setMainHTML(element) {
	element.innerHTML = //
		'<div method="post" \
	            class="editform" \
			       id="editform" \
	   accept-charset="UTF-8" \
		      enctype="application/x-www-form-urlencoded"> \
	<input type="hidden" name="page" value="Sandbox" /> \
	<input type="hidden" name="action" value="save" /> \
	<input type="hidden" name="encodingcheck" value="ぁ" /> \
	<input type="hidden" name="ksttti" value="-1504182443118" /> \
	<input class="hidden" type="text" name="submit_auth" id="submit_auth" value="" /> \
	<div class="snipe"> \
			<div class="form-inline form-group"> \
				<span class="cage"> \
					<button class="btn btn-success" type="submit" name="ok" accesskey="s" onclick="elwiki.PageEditor.save()">Сохранить</button> \
					<!-- (:FVK: добавляется) style="opacity: 0; visibility: hidden;" -->\
					<input class="form-control" id="changenote" data-hover-parent="span" type="text" size="80" maxlength="80" \
						name="changenote" placeholder="Комментарий изменений" value="" /> \
				</span> \
				\
				<div class="btn-group editor-tools"> \
					<div class="btn-group sections"> \
						<button class="btn btn-default"><span class="icon-bookmark"><span class="caret"></span></span></button> \
						<ul class="dropdown-menu" data-hover-parent="div" style="opacity: 0; visibility: hidden;"> \
							<li class="active"><a class="indent-0 section-2">( all )</a></li> \
							<li><a class="indent-0 section-1">Start of Page</a></li> \
							<li class="divider"></li> \
							<li><a class="indent-2 section0">First</a></li> \
							<li><a class="indent-2 section1">Second</a></li> \
						</ul> \
					</div> \
					\
					<div class="btn-group formatting-options"> \
						<button class="btn btn-default"><span class="icon-tint"><span class="caret"></span></span></button> \
						<!-- (:FVK: добавляется)  style="opacity: 0; visibility: hidden;" -->\
						<ul class="dropdown-menu dropdown-menu-horizontal" data-hover-parent="div"> \
							<li><a href="#" data-cmd="bold" title="жирный"><b>bold</b></a></li> \
							<li><a href="#" data-cmd="italic" title="прописной"><i>italic</i></a></li> \
							<li><a href="#" data-cmd="mono" title="моноширинный"><tt>mono</tt></a></li> \
							<li><a href="#" data-cmd="sub" title="подстрочный">a<span class="sub">sub</span></a></li> \
							<li><a href="#" data-cmd="sup" title="надстрочный">a<span class="sup">sup</span></a></li> \
							<li><a href="#" data-cmd="strike" title="подчеркивание"><span class="strike">strike</span></a></li> \
							<li><a href="#" data-cmd="link" title="Вставить вики-ссылку"><span class="icon-link"></span></a></li> \
							<li><a href="#" data-cmd="img" title="Вставить картинку"><span class="icon-picture"></span></a></li> \
							<li><a href="#" data-cmd="plugin" title="Вызов плагина"><span class="icon-puzzle-piece"></span></a></li> \
							<li><a href="#" data-cmd="font" title="Шрифт">Font<span class="caret"></span></a></li> \
							<li><a href="#" data-cmd="chars" title="Специальные символы"><span class="icon-euro"><span class="caret"></span></span></a></li> \
						</ul> \
					</div> \
					\
					 <button class="btn btn-default" data-cmd="undo" title="Отменить изменение [ z ]"><span class="icon-undo"></span></button> \
					 <button class="btn btn-default" data-cmd="redo" title="Redo last Undo"><span class="icon-repeat"></span></button> \
					 <button class="btn btn-default" data-cmd="find"><span class="icon-search"></span></button> \
					\
					<div class="btn-group config"> \
						<button class="btn btn-default"><span class="icon-wrench"></span><span class="caret"></span></button> \
							<!-- style="opacity: 0; visibility: hidden;" --> \
						<ul class="dropdown-menu" data-hover-parent="div"> \
	          				<li><a><label for="autosuggest"><input data-cmd="autosuggest" id="autosuggest" type="checkbox">Auto Suggest</label></a></li> \
							<li><a><label for="tabcompletion"><input data-cmd="tabcompletion" id="tabcompletion" type="checkbox">Tab Completion (keyword+Tab)</label></a></li> \
							<li><a><label for="smartpairs"><input data-cmd="smartpairs" id="smartpairs" type="checkbox">Smart Typing Pairs</label></a></li> \
						<!-- ?? :FVK:deprecated: ??\
							<li class="divider"></li> \
							<li><a><label for="livepreview"><input data-cmd="livepreview" id="livepreview" type="checkbox">Live Preview <span class="icon-refresh"></span></label></a></li> \
							<li><a><label for="previewcolumn"><input data-cmd="previewcolumn" id="previewcolumn" disabled="" type="checkbox">Side by Side Preview <span class="icon-columns"></span></label></a></li> \
						-->\
						</ul> \
					</div> <!-- class="btn-group config" --> \
		<!-- ?? :FVK:deprecated: ??\
					<div class="btn-group config"> \
		    			<button class="btn btn-default"><span class="icon-pencil"></span><span class="caret"></span></button> \
						<ul class="dropdown-menu" data-hover-parent="div" style="opacity: 0; visibility: hidden;"> \
							<li class="active"><a>plain</a></li> \
							<li><a class="editor-type" href="/JSPwiki_ru/Edit.jsp?page=%D0%9F%D0%B5%D1%81%D0%BE%D1%87%D0%BD%D0%B8%D1%86%D0%B0">wysiwyg</a></li> \
						</ul> \
					</div> \
		--> \
				</div> <!-- class="btn-group editor-tools" --> \
				\
				<button class="btn btn-danger pull-right" name="cancel" accesskey="q" title="Cancel editing. Your changes will be lost. [ q ] [q]" type="submit" onclick="elwiki.PageEditor.cancel()">Отменить</button> \
			</div> <!-- class="form-inline form-group" --> \
		\
		\
			<div class="row edit-area"> \
				<div class="col-50"> \
		<!-- (:FVK: в результате клонирования создается `work`-area:) <textarea class="editor form-control" autofocus="autofocus" rows="20" cols="80" style="height: 740px;">text sandbox.</textarea> -->\
		<!-- (:FVK: для id="editorarea", устанавливается при клонировании:) style="display: none;" -->\
					<textarea class="editor form-control" id="editorarea" name="_editedtext" autofocus="autofocus" rows="20" cols="80">text sandbox.</textarea> \
				</div> \
			</div> \
		<!-- :FVK:deprecated:\
	    	<div class="resizer" data-pref="editorHeight" title="Drag to resize the text and preview area"></div> \
		-->\
			<!-- (:FVK: для ajaxpreview дается в run-time) style="height: 740px;" -->\
    		<!-- ?? :FVK:deprecated: ?? <div class="ajaxpreview col-50"> </div> -->\
		\
	</div> <!-- class="snipe" --> \
	</div>';
};
